package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;


/**
 * @author zhoufei
 */
@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录功能控制层
     * @param employee
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request){

        //①. 将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //②. 根据页面提交的用户名username查询数据库中员工数据信息
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee employee1 = employeeService.getOne(queryWrapper);

        //③. 如果没有查询到, 则返回登录失败结果
        if (employee1==null){
            return R.error("登陆失败");
        }

        //④. 密码比对，如果不一致, 则返回登录失败结果
        if (!password.equals(employee1.getPassword())){
            return R.error("密码错误");
        }

        //⑤. 查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (employee1.getStatus()==0){
            return R.error("用户被锁定，登录失败");
        }

        //⑥. 登录成功，将员工id存入Session, 并返回登录成功结果
        request.getSession().setAttribute("employee",employee1.getId());
        return R.success(employee1);
    }


    /**
     * 后台退出系统
     * @return  2
     */
    @PostMapping("/logout")
    public R<Employee> logout(HttpSession session){
        Long empId = (Long) session.getAttribute("employee");
        log.info("后台系统员工退出，员工Id为：{}",empId);

        session.invalidate();//退出系统后session就需要销毁
        return R.success(null);
    }


    /**
     * 新增用户
     * @return
     */
    @PostMapping
    //新增用户所需参数：一个封装成Json的employee对象和request
    public R save(@RequestBody Employee employee, HttpServletRequest request){
        //1.对新增的用户设置默认密码（进行MD5加密），封装到用户对象中
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        //2.用户的创建在页面没有后创建时间信息，和创建人信息，需要手动封装
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //3.还需要封装创建人的信息（该信息是通过登录用户的id获取的）
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);
        //4.调用新增方法，将封装好的对象信息存储到数据库
        employeeService.save(employee);

        return R.success("新增成功");
        //注：因为账号在数据库中设置了唯一属性，所以新增的账号数据库存在时就会报错，此时需要捕捉异常
        //两种方式：第一种对新增语进行try/catch;第二种全局异常处理（推荐使用）
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //1.构造分页构造器
        Page<Employee> pageInfo = new Page<>(page,pageSize);
        //2.构造查询条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
       queryWrapper.like(name !=null,Employee::getName,name);
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询条件
       employeeService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改员工账号状态
     * @PutMapping
     * @param employee
     * @param session
     * @return
     */
    @PutMapping
    public R update(@RequestBody Employee employee,HttpSession session){
//        employee.setUpdateTime(LocalDateTime.now());
//        Long empId = (Long) session.getAttribute("employee");
//        employee.setUpdateUser(empId);

        employeeService.updateById(employee);

        return R.success("修改成功");
    }

    /**
     * 根据Id查询对象信息
     * @return
     */
    @GetMapping ("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);

        if (employee != null){
            return R.success(employee);
        }
        return R.error("查无此人");
    }
}
